package com.aaa.controller;

import com.aaa.entity.Message;
import com.aaa.entity.SysUserEntity;
import com.aaa.entity.Pager;
import com.aaa.service.*;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "UserServlet",urlPatterns = "/user.action")
public class UserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         String method=request.getParameter("method");
            if(method!=null)
            {
                switch (method)
                {
                    case "query":
                    query(request,response);
                    break;
                    case "update":
                        update(request,response);
                        break;
                    case "updateone":
                        updateone(request,response);
                        break;
                    case "deleteuser":
                        deleteuser(request,response);
                        break;
                    case "bindRole":
                        bindRole(request,response);
                        break;
                    case "bindDept":
                        bindDept(request,response);
                        break;
                    case "caidan":
                       caidan(request,response);
                        break;
                    case "checkUserName":
                        checkUserName(request,response);
                        break;

                }
            }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
    private void query(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String pageNo = request.getParameter("pageNo")==null?"1":request.getParameter("pageNo");
        String pageSize = request.getParameter("pageSize")==null?"1":request.getParameter("pageNo");
        Map<String,String> condition=new HashMap<>();
        condition.put("user_name",request.getParameter("user_name"));
        condition.put("sex",request.getParameter("sex"));
        condition.put("remark",request.getParameter("remark"));
        condition.put("status",request.getParameter("status"));

        UserService service=new UserServiceImpl();
        Pager pager=service.query(Integer.valueOf(pageNo),Integer.valueOf(pageSize),condition);
        response.getWriter().print(JSON.toJSONString(pager));
    }
    private void update(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String user_id=request.getParameter("user_id");
        String dept_id = request.getParameter("dept_id");
        String login_name=request.getParameter("login_name");
        String user_name=request.getParameter("user_name");
        String password=request.getParameter("password");
        String email=request.getParameter("email");
        String phonenumber=request.getParameter("phonenumber");
        String sex=request.getParameter("sex");
        String status=request.getParameter("status");
        String remark=request.getParameter("remark");

        String[] roleIds_1=request.getParameterValues("role");
        List<Long> roles=new ArrayList<>();
        for(int i=0;i<roleIds_1.length;i++){
            roles.add(Long.valueOf(roleIds_1[i]));
        }

        SysUserEntity user=new SysUserEntity((long)Integer.valueOf(user_id),Long.valueOf(dept_id),login_name,user_name,password,email,phonenumber,sex,status,remark, roles.toArray(new Long[roles.size()]));
        user.setCreateBy("admin"); //从session中获取
        user.setUpdateBy("admin");

        UserService userservice=new UserServiceImpl();

        Message message= userservice.add(user);
        PrintWriter writer = response.getWriter();
        writer.print(JSON.toJSONString(message));
    }
    private void updateone(HttpServletRequest request, HttpServletResponse response) throws IOException
    {
        String user_id=request.getParameter("user_id");
        UserService service=new UserServiceImpl();
        Map map=service.queryid(Integer.valueOf(user_id));
        String str= JSON.toJSONStringWithDateFormat(map,"yyyy-MM-dd");
        response.getWriter().print(str);
    }
    private void deleteuser(HttpServletRequest request, HttpServletResponse response) throws IOException
    {
        String user_id=request.getParameter("user_id");
        UserService service=new UserServiceImpl();
        int res=service.delete(Integer.parseInt(user_id));
        String str=JSON.toJSONString(res);
        response.getWriter().print(str);
    }
    private void bindRole(HttpServletRequest request, HttpServletResponse response) throws IOException {
        RoleService service=new RoleServiceImpl();
        List list=service.query();
        response.getWriter().print(JSON.toJSONString(list));

    }
    private void bindDept(HttpServletRequest request, HttpServletResponse response) throws IOException {
        DeptService service=new DeptServiceImpl();
        List list=service.query();
        response.getWriter().print(JSON.toJSONString(list));
    }
    private void caidan(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session=request.getSession();
      int userid=Integer.valueOf(String.valueOf(session.getAttribute("user")));
      MenuService service=new MenuServiceImpl();
      List list=service.queryMenuByUserId(userid);
      String str=JSON.toJSONStringWithDateFormat(list,"yyyy-MM-dd");
      PrintWriter writer=response.getWriter();
      writer.print(str);
    }
    private void checkUserName(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        //返回json数据，格式为{"valid",true}	表示合法，验证通过。{"valid":false} 表示不合法，验证不通过
        String jsonResult = "";
        String login_name = request.getParameter("login_name");
        //去数据进行唯一性确认
        if (login_name!=null) {
            //服务层service调用数据库访问层dao中的searchUserName方法。
            UserService service=new UserServiceImpl();
            List res = service.selectloginname(login_name);
            if (res.size()!=0) {
                //如果名称存在
                jsonResult = "{\"valid\":false}";
            }else{
                //如果该名称不存在
                jsonResult = "{\"valid\":true}";
            }
        } else {
            jsonResult = "{\"valid\":false}";
        }
        //response把jsonResult打到前台
        response.getWriter().write(jsonResult);
    }



}
